<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 第三方服务
 *
 * @author      Eden
 * @datetime    2016/12/7 17:56
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Device extends ADM_Controller
{
    const PAGE_SIZE = 20;

    // 错误信息
    private $error = '';

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $this->load->view(parent::TMP_DIR . '/stream/index.html');
    }

    public function detail()
    {

        $deviceId = $this->input->get('deviceId');
        if (empty($deviceId)) {
            show_404();
            exit;
        }

        $this->load->model('admin/stream/Device_Model', 'stream');
        $res = $this->stream->getDetail($deviceId);
        if (empty($res)) {
            show_404();
            exit;
        }
        $this->load->view(parent::TMP_DIR. '/stream/detail.html', array(
            'detail' => $res
        ));
    }

    /**
     * 删除设备
     */
    public function deleteDevice()
    {
        $send['state'] = false;
        do {

            $deviceSerial = '660403304';
            $this->load->library('util/Util_Ys', 'ys');
            if ($this->ys->deleteDevice($deviceSerial)) {
                $send['state'] = true;
            } else {
                $send['error'] = $this->ys->getError();
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * 获取列表
     */
    public function getLists()
    {
        $send['state'] = false;
        do {

            $params = $this->input->get();
            $page = !empty($params['page']) && intval($params['page']) > 0 ? intval($params['page']) : 1;
            $keyword = !empty($params['keyword']) ? $params['keyword'] : '';

            $this->load->model('admin/stream/Device_Model', 'stream');

            $offset = ($page - 1) * self::PAGE_SIZE;
            $lists = $this->stream->getLists($offset, self::PAGE_SIZE, $keyword);
            if ($lists) {
                $send['state'] = true;
                $send['data'] = $lists;
            } else {
                $send['error'] = '列表获取失败';
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 获取所有信息
     */
    public function getAll()
    {
        $send['state'] = false;
        do {
            $this->load->model('admin/stream/Device_Model', 'stream');
            $lists = $this->stream->getAllLists();
            if ($lists) {
                $send['state'] = true;
                $send['data'] = $lists;
            } else {
                $send['error'] = '列表获取失败';
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 添加设备
     */
    public function doAddDevice()
    {
        $send['state'] = false;
        do {

            $params = $this->input->post();
            if (empty($params['groupId']) || empty($params['deviceSerial']) || empty($params['deviceName'])
            || empty($params['validateCode'])) {
                $send['error'] = '参数错误';
                break;
            }

            if (!preg_match('/^\d{9}$/', $params['deviceSerial'])) {
                $send['error'] = '序列号格式错误';
                break;
            }

            if (!preg_match('/^\w{6}$/', $params['validateCode'])) {
                $send['error'] = '验证码格式错误';
                break;
            }

            $res = $this->_doAdd($params);
            if (!$res) {
                $send['error'] = !empty($this->error) ? $this->error : "设备添加失败";
                break;
            }

            try {
                $this->load->model('admin/stream/Device_Model', 'stream');
                if ($deviceInfo = $this->stream->doAddDevice($res)) {
                    $send['state'] = true;
                    $send['data'] = $deviceInfo;
                } else {
                    $send['error'] = '设备添加失败';
                }
            } catch(Exception $e) {
                $send['error'] = $e->getMessage();
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 发起接口请求
     * @param array $params
     * @return array|bool
     */
    private function _doAdd(Array $params)
    {
        $this->load->library('util/Util_Ys', null, 'ys');
        // 执行添加操作,再去修改设备信息,然后再修改数据库
        try {
            // 添加
            $params['validateCode'] = strtoupper($params['validateCode']);
            if (!$this->ys->deviceAdd($params['deviceSerial'], $params['validateCode'])) {
                $err = $this->ys->getError();
                $this->error = !empty($err) ? $err : '设备添加失败';
                return false;
            }

            // 修改
            if (!$this->ys->deviceEditName($params['deviceSerial'], $params['deviceName'])) {
                $err = $this->ys->getError();
                $this->error = !empty($err) ? $err : '设备名称写入失败';
                return false;
            }

            // 获取单个设备信息
            if (!$this->ys->deviceInfo($params['deviceSerial'])) {
                $err = $this->ys->getError();
                $this->error = !empty($err) ? $err : '设备信息拉取失败';
                return false;
            }

            $data = $this->ys->getData();
            if (empty($data)) {
                $this->error = '设备信息拉取失败';
                return false;
            }

            return array(
                'groupId' => $params['groupId'],
                'deviceSerial' => value($params, 'deviceSerial'),
                'deviceName' => $params['deviceName'],
                'validateCode' => $params['validateCode'],
                'model' => value($data, 'model', ''),
                'status' => value($data, 'status', 0),
                'defence' => value($data, 'defence', 0),
                'isEncrypt' => value($data, 'isEncrypt', 0),
                'created' => dateTime()
            );

        } catch(Exception $e) {
            $this->error = $e->getMessage();
        }
        return false;
    }

    /**
     * 保存配置修改
     */
    public function saveDevice()
    {
        $send['state'] = false;
        do {

            $params = $this->input->post();
            if (empty($params['deviceId'])) {
                $send['error'] = '无效设备';
                break;
            }

            if (empty($params['groupId']) || empty($params['deviceName'])
                || empty($params['videoUrlHD']) || empty($params['videoUrlSD'])) {
                $send['error'] = '有必填项没有填写';
                break;
            }

            $this->load->model('admin/stream/Device_Model', 'stream');
            if ($this->stream->editDevice($params)) {
                $send['state'] = true;
                break;
            }
            $send['error'] = '设置保存失败';

        } while(false);
        $this->output->send($send);
    }
}
